package com.demo.rocketmq.config;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.demo.rocketmq.config.properties.RocketMqConfigPropertites;
import com.demo.rocketmq.constants.RocketMqConstants;
import com.demo.rocketmq.mapper.RetrySendMsgMapper;
import com.demo.rocketmq.producer.SendAndCallbackProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;

/**
 * rocketmq 消息重发mybatis配置
 * @author cyj
 */
@Slf4j
@Configuration
@ConditionalOnClass({MybatisPlusAutoConfiguration.class, RocketMQTemplate.class})
@AutoConfigureAfter(MybatisPlusAutoConfiguration.class)
@MapperScan("com.demo.mq.rocketmq.mapper")
@ConditionalOnProperty(prefix = RocketMqConstants.CALLBACK_PROPERTIES, name = "enable", havingValue = "true")
@EnableConfigurationProperties(RocketMqConfigPropertites.class)
public class MybatisConfig implements SmartInitializingSingleton, ApplicationContextAware {

    private final RetrySendMsgMapper retrySendMsgMapper;

    private ApplicationContext applicationContext;

    public MybatisConfig(RetrySendMsgMapper retrySendMsgMapper) {
        log.info("MybatisConfig 初始化");

        this.retrySendMsgMapper = retrySendMsgMapper;
    }

    /**
     * 将mapper注入RocketMqProducerImpl对象
     */
    @Override
    public void afterSingletonsInstantiated() {
        SendAndCallbackProducer mqProducer = applicationContext.getBean(SendAndCallbackProducer.class);
        mqProducer.setRetrySendMsgMapper(retrySendMsgMapper);
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
